<?php
namespace control;

// 设备
class equipmentClass extends adIndexClass
{
	private const page       = 'equipment';
	private const table      = 'equipment';
	private const tableDepr  = 'equipment_depreciation';
	private const tableMotor = 'equipment_motor_spec';
	private const title      = '设备管理';
	private const state      = ['正常', '维修中', '已核减'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case '':
                $tr = [
                    'type'          => [
                        'name'  => "变动类型",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'department'  => [
                        'name'  => '使用部门',
                        'width' => 200,
                    ],
                    'storage'         => [
                        'name'  => '存放地点',
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '变动日期',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'type'          => [
                        'name'  => "设备类别",
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => '设备编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '设备名称',
                        'width' => 200,
                    ],
                    'factory'          => [
                        'name'  => '厂家',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'factoryDdate'          => [
                        'name'  => '出厂日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => '登记日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 获取设备名称
     * @param $id
     * @param bool $short
     * @param string $interval
     * @return mixed|string
     */
    public static function getName($id,$short = true,$interval = '-'){
        $info = query(self::table,"id = '$id'");
        if (empty($info['id'])){
            return '';
        }
        return $short?$info['name']:$info['code'].$interval.$info['name'];
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "设备类别" => select(['name' => "type", 'option' => explode('，', para(self::page . 'Type'))]),
                    "设备编号"   => text(array("name" => "code")),
                    "设备名称"   => text(array("name" => "name")),
                ],
                [
                    "规格型号"   => text(array("name" => "model")),
                    "登记日期"   => text(array("name" => "date")),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        // 打印
        if ($this->power(self::page, "print")) {
            $button .= '<a href="javascript:;" onclick="printPage(\'' . $this->get('cla') . '\')" class="spanButton">打印</a>';
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		if ($this->post('state')) {
			$where = " AND state = '" . $this->post('state') . "'  ";
		} else {
			$where = " AND state <> '已核减' ";
		}
		//查询结果
		$equal = [
			'type' => $this->post('type'),
			'coid' => self::$coid,
		];
		$like  = [
			'code'  => $this->post('code'),
			'name'  => $this->post('name'),
			'model' => $this->post('model'),
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('date')) {
			$where .= self::timeComparison($this->post('date'), 'date', 'time');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				"edit"   => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'time':
                        $row[] = self::formatDate($array['time']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }  else {
            $exampleData[] = [
                '机床', 'GW001', '智能高温炉', '', '', '', '', '', '', '', '', '', '', '', '', '(样例数据，导入时请删除本条数据)', '120000', '0', '80000', '直线折旧法', '0', '10', 'DP0007', '总经办', '厂房', 'YM202112310004', '李红',
            ];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '设备类别'=>$example[0],
                            '设备编号'=>$example[1],
                            '设备名称'=>$example[2],
                            '规格型号'=>$example[3],
                            '设备用途'=>$example[4],
                            '生产厂家'=>$example[5],
                            '出厂日期'=>$example[6],
                            '进厂日期'=>$example[7],
                            '安装日期'=>$example[8],
                            '投产日期'=>$example[9],
                            '安装图图号'=>$example[10],
                            '安装图存放位置'=>$example[11],
                            '出厂编号'=>$example[12],
                            '设备来源'=>$example[13],
                            '外形尺寸'=>$example[14],
                            '备注'=>$example[15],
                            '资产原值'=>$example[16],
                            '累计折旧'=>$example[17],
                            '净残值'=>$example[18],
                            '折旧方式'=>$example[19],
                            '使用期限'=>$example[20],
                            '折旧期限'=>$example[21],
                            '使用部门编号'=>$example[22],
                            '使用部门'=>$example[23],
                            '存放地点'=>$example[24],
                            '管理员编号'=>$example[25],
                            '管理员'=>$example[26],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text   = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x    = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $equipment = query("equipment"," coid = '".self::$coid."' and code = '$cell[设备编号]' ");
                    $id = empty($equipment['id'])?suiji():$equipment['id'];
                    $types = explode('，', para(self::page . 'Type'));
                    $depreciationMethod = explode('，', para('depreciationMethod'));
                    $department = query("department"," orderNo = '$cell[使用部门编号]' ");
                    $staff = query("staff"," orderNo = '$cell[管理员编号]' ");
                    $field      = [
                        'type'    => $cell['设备类别'],
                        'code'    => $cell['设备编号'],
                        'name'    => $cell['设备名称'],
                        'model'   => $cell['规格型号'],
                        'uses' => $cell['设备用途'],
                        'factory'    => $cell['生产厂家'],
                        'factoryDdate'   => self::importDateFormat($cell['出厂日期']),
                        'entryDate'   => self::importDateFormat($cell['进厂日期']),
                        'installDate'   => self::importDateFormat($cell['安装日期']),
                        'launchDate'   => self::importDateFormat($cell['投产日期']),
                        'figureNo'    => $cell['安装图图号'],
                        'figureLocation'    => $cell['安装图存放位置'],
                        'factoryNo'    => $cell['出厂编号'],
                        'source'    => $cell['设备来源'],
                        'size'    => $cell['外形尺寸'],
                        'text'    => $cell['备注'],
                    ];
                    $annotation = [
                        'type'           => '设备类别',
                        'code'           => '设备编号',
                        'name'           => '设备名称',
                        'model'          => '规格型号',
                        'uses'           => '设备用途',
                        'factory'        => '生产厂家',
                        'factoryDdate'   => '出厂日期',
                        'entryDate'      => '进厂日期',
                        'installDate'    => '安装日期',
                        'launchDate'     => '投产日期',
                        'figureNo'       => '安装图图号',
                        'figureLocation' => '安装图存放位置',
                        'factoryNo'      => '出厂编号',
                        'source'         => '设备来源',
                        'size'           => '外形尺寸',
                        'text'           => '备注',
                    ];
                    $rules      = [
                        'type' => 'required',
                        'code' => 'required',
                        'name' => 'required',
                    ];

                    $deprField      = [
                        'eqid'               => $id,
                        'assetPrice'         => $cell['资产原值'],
                        'cumulative'         => $cell['累计折旧'],
                        'netSalvage'         => $cell['净残值'],
                        'type'               => $cell['折旧方式'],
                        'usePeriod'          => $cell['使用期限'],
                        'depreciationPeriod' => $cell['折旧期限'],
                        'departmentId'       => $department['id'],
                        'stid'               => $staff['stid'],
                        'storageLocation'    => $cell['存放地点'],
                    ];
                    $deprAnnotation = [
                        'eqid'               => '设备ID',
                        'assetPrice'         => '资产原值',
                        'cumulative'         => '累计折旧',
                        'netSalvage'         => '净残值',
                        'type'               => '折旧方式',
                        'usePeriod'          => '使用期限(月)',
                        'depreciationPeriod' => '折旧期限(月)',
                        'departmentId'       => '使用部门',
                        'stid'               => '管理员',
                        'storageLocation'    => '存放地点',
                    ];
                    $deprRules      = [
                        'eqid'               => 'required',
                        'assetPrice'         => 'required',
                        'netSalvage'         => 'required',
                        'type'               => 'required',
                        'depreciationPeriod' => 'required',
                        'departmentId'       => 'required',
                        'stid'               => 'required',
                        'storageLocation'    => 'required',
                    ];
                    $equipment_depreciation = query("equipment_depreciation"," coid = '".self::$coid."' and eqid = '$id' ");
                    // 合并验证
                    $annotationArr = array_merge($annotation, $deprAnnotation);
                    $fieldArr      = array_merge($field, $deprField);
                    $rulesArr      = array_merge($rules, $deprRules);
                    // 校验是否符合规则
                    $vt     = new \verify();
                    $result = $vt->setAliases($annotationArr)->validate($fieldArr, $rulesArr)->isOk();
                    if ($result === false) {
                        $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                    }elseif(!in_array($field['type'],$types)){
                        $text .= "\n第【{$row_list}】行，设备类别不在系统设定范围内";
                    }elseif(!in_array($deprField['type'],$depreciationMethod)){
                        $text .= "\n第【{$row_list}】行，折旧方式不在系统设定范围内";
                    } else {
                        // 新增
                        if (static::isNull($equipment['id'])) {
                            $field   = array_merge($field, [
                                'id'    => $id,
                                'state' => '正常',
                                'coid'  => self::$coid,
                                'stid'  => $this->control['stid'],
                            ]);
                            $warn    = static::insert([
                                "table" => self::table,
                                "field" => $field,
                            ]);
                        } else {
                            $warn = static::update([
                                "table" => self::table,
                                "field" => $field,
                                'where' => " id = '".$equipment['id']."' ",
                            ]);
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            if (static::isNull($equipment_depreciation['id'])) {
                                $field   = array_merge($deprField, [
                                    'id'        => self::getId(),
                                    'coid'      => self::$coid,
                                    'orderDate' => $this->date,
                                ]);
                                static::insert([
                                    "table" => self::tableDepr,
                                    "field" => $field,
                                ]);
                            } else {
                                static::update([
                                    "table" => self::tableDepr,
                                    "field" => $deprField,
                                    'where' => " coid = '".self::$coid."' and eqid = '$id' ",
                                ]);
                            }
                            $x++;
                            $text .= "第【{$row_list}】行数据导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$depr     = query(self::tableDepr, " eqid = '$info[id]' ");
		$button[]  = [
			"name"  => L('public.save'),
			"type"  => "点击事件",
			"cla"   => $this->get('cla'),
			"fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
			"post"  => ["id" => $this->get('id')],
			'style' => 'li-btn-blue-bg',
		];
		$tr[]     = ['', '位置', '功率', '型号', '接线方式', '电压', '频率'];
        $result = find(array(
            'field' => "id as mxId,location,power,model as m_model,wiring,voltage,frequency",
            'table' => self::tableMotor." where eqid = '$info[id]' order by time"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->listRow($array);
            }
        }else{
            $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
        }
        $table = $this->listTable(['tr' => $tr, 'end' => true]);
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '设备类别' => select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => explode('，', para(self::page . 'Type'))]),
                    must . '设备编号' => text(['name' => "code", 'class' => 'text', 'value' => $info['code']]),
                    must . '设备名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    '规格型号'        => text(['name' => "model", 'class' => 'text', 'value' => $info['model']]),
                ],
                [
                    '设备用途' => text(['name' => "uses", 'class' => 'text', 'value' => $info['uses']]),
                    '生产厂家' => text(['name' => "factory", 'class' => 'text', 'value' => $info['factory']]),
                    '出厂日期' => text(['name' => "factoryDdate", 'class' => 'text', 'value' => $info['factoryDdate'], 'laydate' => ['date']]),
                    '进厂日期' => text(['name' => "entryDate", 'class' => 'text', 'value' => $info['entryDate'], 'laydate' => ['date']]),
                ],
                [
                    '安装日期' => text(['name' => "installDate", 'class' => 'text', 'value' => $info['installDate'], 'laydate' => ['date']]),
                    '投产日期' => text(['name' => "launchDate", 'class' => 'text', 'value' => $info['launchDate'], 'laydate' => ['date']]),
                    '安装图图号'   => text(['name' => "figureNo", 'class' => 'text', 'value' => $info['figureNo']]),
                    '安装图存放位置' => text(['name' => "figureLocation", 'class' => 'text', 'value' => $info['figureLocation']]),
                ],
                [
                    '出厂编号' => text(['name' => "factoryNo", 'class' => 'text', 'value' => $info['factoryNo']]),
                    '设备来源' => text(['name' => "source", 'class' => 'text', 'value' => $info['source']]),
                    '外形尺寸' => text(['name' => "size", 'class' => 'text', 'value' => $info['size']]),
                ],
                [
                    '备注'   => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
                [
                    '设备图片' => fileUploadClass::addImgComponent($id, '设备图片', self::page, self::page . 'EditForm'),
                ],
            ],
            '资产折旧' => [
                [
                    must . '资产原值' => text(['name' => "assetPrice", 'class' => 'text', 'value' => $depr['assetPrice'], 'unit' => static::$unit]),
                    '累计折旧'        => text(['name' => "cumulative", 'class' => 'text', 'value' => $depr['cumulative'], 'unit' => static::$unit]),
                    must . '净残值'  => text(['name' => "netSalvage", 'class' => 'text', 'value' => $depr['netSalvage'], 'unit' => static::$unit]),
                    must . '折旧方式' => select(['name' => "deprType", 'class' => 'text', 'value' => $depr['type'], 'option' => explode('，', para('depreciationMethod'))]),
                ],
                [
                    '使用期限'        => text(['name' => "usePeriod", 'class' => 'text', 'value' => $depr['usePeriod'], 'unit' => '月']),
                    must . '折旧期限' => text(['name' => "depreciationPeriod", 'class' => 'text', 'value' => $depr['depreciationPeriod'], 'unit' => '月']),
                    must . '使用部门' => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '使用部门', 'value' => $depr['departmentId']]),
                    must . '存放地点' => text(['name' => "storageLocation", 'class' => 'text', 'value' => $depr['storageLocation']]),
                ],
                [
                    must . '管理员' => selectMultiple(["name" => "deprStid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '管理员', 'value' => $depr['stid']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '电动机规格',
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);

		$data['html'] .= <<<EOT
<script>
 function addRow(e){
     $.post(root+'control/adIndex.php?cla={$this->get('cla')}&fun=addRow',{},function (res){
        $(e).closest('tr').after(res.data);
        resetNumber($(e).closest('tbody'))  
     },'json');
 }

</script>
EOT;
		//返回
		return $this->tab($data);
	}

    /**
     * Desc : 电动机规格
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['location', 'power', 'm_model', 'wiring', 'voltage', 'frequency'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            text(['name' => 'location[]', 'value' => $array['location'], 'title' => '请填写']),
            text(['name' => 'power[]', 'value' => $array['power'], 'title' => '请填写']),
            text(['name' => 'm_model[]', 'value' => $array['m_model'], 'title' => '请填写']),
            text(['name' => 'wiring[]', 'value' => $array['wiring'], 'title' => '请填写']),
            text(['name' => 'voltage[]', 'value' => $array['voltage'], 'title' => '请填写']),
            text(['name' => 'frequency[]', 'value' => $array['frequency'], 'title' => '请填写'])
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * 添加一行
     *
     * @return bool|string
     */
    public function addRow()
    {

        $res = json_decode($this->listRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$fileIdArr  = $this->post('imgId');
		$mxId       = $this->post('mxId') ?: [];
		$location   = $this->post('location');
		$power      = $this->post('power');
		$model      = $this->post('m_model');
		$wiring     = $this->post('wiring');
		$voltage    = $this->post('voltage');
		$frequency  = $this->post('frequency');
		$field      = [
			'type'           => $this->post('type'),
			'code'           => $this->post('code'),
			'name'           => $this->post('name'),
			'model'          => $this->post('model'),
			'uses'           => $this->post('uses'),
			'factory'        => $this->post('factory'),
			'factoryDdate'   => $this->post('factoryDdate'),
			'entryDate'      => $this->post('entryDate'),
			'installDate'    => $this->post('installDate'),
			'launchDate'     => $this->post('launchDate'),
			'figureNo'       => $this->post('figureNo'),
			'figureLocation' => $this->post('figureLocation'),
			'factoryNo'      => $this->post('factoryNo'),
			'source'         => $this->post('source'),
			'size'           => $this->post('size'),
			'text'           => $this->post('text'),
		];
		$annotation = [
			'type'           => '设备类别',
			'code'           => '设备编号',
			'name'           => '设备名称',
			'model'          => '规格型号',
			'uses'           => '设备用途',
			'factory'        => '生产厂家',
			'factoryDdate'   => '出厂日期',
			'entryDate'      => '进厂日期',
			'installDate'    => '安装日期',
			'launchDate'     => '投产日期',
			'figureNo'       => '安装图图号',
			'figureLocation' => '安装图存放位置',
			'factoryNo'      => '出厂编号',
			'source'         => '设备来源',
			'size'           => '外形尺寸',
			'text'           => '备注',
		];
		$rules      = [
			'type' => 'required',
			'code' => 'required',
			'name' => 'required',
			// 'model'          => 'required',
			// 'uses'           => 'required',
			// 'factory'        => 'required',
			// 'factoryDdate'   => 'required',
			// 'entryDate'      => 'required',
			// 'installDate'    => 'required',
			// 'launchDate'     => 'required',
			// 'figureNo'       => 'required',
			// 'figureLocation' => 'required',
			// 'factoryNo'      => 'required',
			// 'source'         => 'required',
			// 'size'           => 'required',
			// 'state'          => 'required',
			// 'text'           => 'required',
		];

		$deprField      = [
			'eqid'               => $id,
			'assetPrice'         => $this->post('assetPrice'),
			'cumulative'         => $this->post('cumulative'),
			'netSalvage'         => $this->post('netSalvage'),
			'type'               => $this->post('deprType'),
			'usePeriod'          => $this->post('usePeriod'),
			'depreciationPeriod' => $this->post('depreciationPeriod'),
			'departmentId'       => $this->post('departmentId'),
			'stid'               => $this->post('deprStid'),
			'storageLocation'    => $this->post('storageLocation'),
		];
		$deprAnnotation = [
			'eqid'               => '设备ID',
			'assetPrice'         => '资产原值',
			'cumulative'         => '累计折旧',
			'netSalvage'         => '净残值',
			'type'               => '折旧方式',
			'usePeriod'          => '使用期限(月)',
			'depreciationPeriod' => '折旧期限(月)',
			'departmentId'       => '使用部门',
			'stid'               => '管理员',
			'storageLocation'    => '存放地点',
		];
		$deprRules      = [
			'eqid'               => 'required',
			'assetPrice'         => 'required',
			// 'cumulative'         => 'required',
			'netSalvage'         => 'required',
			'type'               => 'required',
			// 'usePeriod'          => 'required',
			'depreciationPeriod' => 'required',
			'departmentId'       => 'required',
			'stid'               => 'required',
			'storageLocation'    => 'required',
		];

		// 合并验证
		$annotationArr = array_merge($annotation, $deprAnnotation);
		$fieldArr      = array_merge($field, $deprField);
		$rulesArr      = array_merge($rules, $deprRules);
		$json          = [];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotationArr)->validate($fieldArr, $rulesArr)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} /** elseif (!empty($info['id']) && $info['state'] == '已确认') {
		 * $json['warn'] = '此调拨单已确认，不能修改';
		 * }**/
		else {
			// 电机规格
			/*if (!static::is_null_array($mxId)) {
				if (static::is_null_array($location)) {
					$json['warn'] = '请填写电动机位置';
				} elseif (static::is_null_array($power)) {
					$json['warn'] = '请填写电动机功率';
				} elseif (static::is_null_array($model)) {
					$json['warn'] = '请填写电动机型号';
				} elseif (static::is_null_array($wiring)) {
					$json['warn'] = '请填写电动机接线方式';
				} elseif (static::is_null_array($voltage)) {
					$json['warn'] = '请填写电动机电压';
				} elseif (static::is_null_array($frequency)) {
					$json['warn'] = '请填写电动机频率';
				}
			}
			if (!empty($json['warn'])) {
				goto resp;
			}*/
			$this->startTrans();
			$isPass = true;//事务通过标志
			// 清理数据
			delete(['table' => self::tableMotor, 'where' => generateWhere(['coid' => self::$coid, 'eqid' => $id,]),]);
			delete(['table' => self::tableDepr, 'where' => generateWhere(['coid' => self::$coid, 'eqid' => $id,]),]);
			if (empty($info['id'])) {
				$field        = array_merge($field, [
					'id'    => $id,
					'state' => '正常',
					'coid'  => self::$coid,
					'stid'  => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
				// 登记设备
				self::equipmentRecord([
					'eqid'         => $id,
					'type'         => '登记',
					'departmentId' => $deprField['departmentId'],
					'storage'      => $deprField['storageLocation'],
					'text'         => $field['text'],
				]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			// 更新折旧
			if (!static::isNull($id)) {
				$field = array_merge($deprField, [
					'id'        => self::getId(),
					'coid'      => self::$coid,
					'orderDate' => $this->date,
				]);
				$warn  = static::insert(["table" => self::tableDepr, "field" => $field,]);
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = $warn;
					goto resp;
				}
			}
			// 更新文件
			if (is_array($fileIdArr)) {
				$warn = update([
					'table' => 'file',
					'field' => ['targetId' => $id],
					'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')",
				]);
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = $warn;
					$isPass       = false;
				}
			}
			//添加或更新报价单明细
			if (is_array($mxId)) {
				foreach ($mxId as $k => $mid) {
                    $mxField = [
                        'location'  => $location[$k],
                        'power'     => $power[$k],
                        'model'     => $model[$k],
                        'wiring'    => $wiring[$k],
                        'voltage'   => $voltage[$k],
                        'frequency' => $frequency[$k],
                    ];
                    if(empty(array_filter($mxField, 'strlen'))) {
                        continue;
                    }
					$warn = static::insert([
						"table" => self::tableMotor,
						"field" => array_merge($mxField, [
							'id'        => $mid,
							'coid'      => self::$coid,
							'eqid'      => $id,
							'stid'      => self::$stid,
						])
					]);
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data   = [
				"id"   => $info['id'],
				"menu" => [
					"detail"      => "基本信息",
					"parts"       => ["name" => "配件", "cla" => "parts", "fun" => "parts"],
					"inspection"  => ["name" => "巡检计划", "cla" => "equipmentInspection", "fun" => "inspection"],
					"maintenance" => ["name" => "保养计划", "cla" => "equipmentMaintenance", "fun" => "maintenance"],
					"failure"     => ["name" => "故障类型", "cla" => "equipment", "fun" => "failure"],
					"file"        => ["name" => "附件", "cla" => "file", "fun" => "equipmentFile"],
					"record"      => ["name" => "变动记录", "cla" => "equipment", "fun" => "record"],
				],
			];
			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
				$button[] = [
					"name"  => "编辑",
					"type"  => "顶部页卡",
					"title" => "编辑用户",
					"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
					'style' => 'li-btn-blue-bg',
				];
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name" => "提交",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "print")) {
				$button[] = [
					"name" => "打印卡片",
					"type" => "外部链接",
					"url"  => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=printPage&body=' . $info['id'],
				];
			}
			if ($this->power(self::page, "state") && in_array($info['state'], ['正常', '维修中'])) {
				$state    = ($info['state'] === '正常') ? '维修中' : '正常';
				$button[] = [
					"name" => $state,
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["id" => $info['id'], 'act' => 'changeState', 'state' => $state],
				];
			}
			$motorTr[] = ['位置', '功率', '型号', '接线方式', '电压', '频率'];
			$result    = find(['table' => self::tableMotor, 'where' => "eqid = '$info[id]' order by time"]);
			foreach ($result['array'] as $array) {
				$motorTr[] = [$array['location'], $array['power'], $array['model'], $array['wiring'], $array['voltage'], $array['frequency'],];
			}
			// 查询部门
			$depr       = query(self::tableDepr, " eqid = '$info[id]' ");
			$department = query('department', " id = '{$depr['departmentId']}' ");
			$editBtn    = <<<EOT
<img onclick="layer('{$this->get('cla')}', 'deprEdit', {eqid: '{$info['id']}'})" alt="editBtn" class="detail-edit-img" src="{$this->root}img/control/edit.svg">
EOT;

			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				"基本信息"              => [
					[
						"设备类别" => $info['type'],
						"设备编号" => $info['code'],
						"设备名称" => $info['name'],
                        "规格型号" => $info['model'],
					],
					[
						"设备用途" => $info['uses'],
						"生产厂家" => $info['factory'],
                        "出厂日期" => $info['factoryDdate'],
                        "进厂日期" => $info['entryDate'],
					],
					[
						"安装日期" => $info['installDate'],
						"投产日期"    => $info['launchDate'],
						"安装图图号"   => $info['figureNo'],
						"安装图存放位置" => $info['figureLocation'],
					],
					[
						"出厂编号" => $info['factoryNo'],
						"设备来源" => $info['source'],
						"外形尺寸" => $info['size'],
					],
					[
						"备注" => pre($info['text']),
					],
				],
				"折旧信息"              => [
					[
						"资产原值（".static::$unit."）" => $depr['assetPrice'],
						"累计折旧（".static::$unit."）" => $depr['cumulative'],
                        "净残值（".static::$unit."）"  => $depr['netSalvage'],
                        "使用期限（月）" => $depr['usePeriod'],
					],
					[
						"折旧期限（月）" => $depr['depreciationPeriod'],
						"部门"  => $department['name'],
						"管理员" => self::findStaff($depr['stid']),
					],
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '电动机规格',
                'html' => $this->listTable(['tr' => $motorTr, 'showSort' => true]),
            ]);
            $data['html'] .= $this->tableShow([
                "当前使用部门" . $editBtn => [
                    [
                        "变动日期" => $depr['orderDate'],
                        "使用部门" => $department['name'],
                        "存放地点" => $depr['storageLocation'],
                    ],
                    [
                        "备注" => pre($depr['text']),
                    ],
                ],
                "设备图片"              => [
                    [
                        fileUploadClass::showImg($info['id'], '设备图片'),
                    ],
                ],
                "系统信息"              => [
                    [
                        "固定资产编码" => $info['code'],
                        "登记人"    => self::findStaff($info['stid']),
                        "登记时间"   => self::formatDate($info['time']),
                        "更新时间" => self::null($info['updateTime']),
                    ],
                ],
                "设备卡片"              => [
                    [
                        self::qrBox($info, $department),
                    ],
                ],
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 弹窗编辑
	 *
	 * @return string
	 */
	public function deprEdit(): string
	{
		$info = query(self::tableDepr, " eqid = '" . $this->post('eqid') . "' ");
		$html = $this->layerEdit([
			"table"  => [
				[
					must . '变动日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => ['type' => 'date']]),
				],
				[
					must . '使用部门' => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '使用部门', 'value' => $info['departmentId']]),
				],
				[
					must . '存放地点' => text(['name' => "storageLocation", 'class' => 'text', 'value' => $info['storageLocation']]),
				],
				[
					'备注' => text(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
				],
			],
			'hidden' => hidden(['name' => 'eqid', 'value' => $info['eqid']]),
		]);
		//返回
		return $this->layer(array(
		    "title" => "编辑",
            'width' => 900,
            'height' => 300,
            "html" => $html,
            'button' => '<button class="button left-bottom" onclick="subForm(\'' . self::page . 'DeprEditForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=deprEditEdit\')">保存</button>'
        ));
	}

	/**
	 * 弹窗编辑
	 *
	 * @return string
	 */
	public function deprEditEdit(): string
	{
		$eqid       = $this->post('eqid');
		$field      = [
			"orderDate"       => $this->post('orderDate'),
			"departmentId"    => $this->post('departmentId'),
			"storageLocation" => $this->post('storageLocation'),
			'text'            => $this->post('text'),
		];
		$annotation = [
			"orderDate"       => '变动日期',
			"departmentId"    => '使用部门',
			"storageLocation" => '存放地点',
		];
		$rules      = [
			"orderDate"       => 'required|date',
			"departmentId"    => 'required',
			"storageLocation" => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND eqid = '$eqid' ";
		$info  = query(self::tableDepr, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (empty($info['id'])) {
			$json['warn'] = "参数错误";
		} else {
			$this->startTrans();
			unset($field['eqid']);
			$json['warn'] = static::update([
				"table" => self::tableDepr,
				"field" => $field,
				"where" => $where,
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				self::equipmentRecord([
					'eqid'         => $eqid,
					'type'         => '编辑使用部门',
					'departmentId' => $field['departmentId'],
					'storage'      => $field['storageLocation'],
					'text'         => $field['text'],
				]);
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $eqid . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	// 操作中转
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = $word = false; // 需要密码
		$form   = $power = '';
		$append = [];
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此调拨单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'changeState':
				$act      = 'state';
				$msg      = self::title . '修改状态';
				$title    = self::table . 'Change';
				$function = 'changeState';
				$form     = self::page . 'OperateForm, detailForm';
				if ($this->post('state')) {
					$append = [
						0 => hidden(['name' => 'state', 'value' => $this->post('state')]),
					];
				}
				$power = '';
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 修改状态
	 *
	 * @return bool|string
	 */
	public function changeState(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$state = $this->post('state');
		$act   = 'state';
		$json  = [];
		if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 修改field
			$fieldKey = 'state';
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if (static::isNull($info['id']) || $info['state'] == $state) {
					continue;
				}
				$fieldVlaue = ($info['state'] == '正常') ? '维修中' : '正常';
				// 修改状态
				static::update([
					"table" => self::table,
					'field' => [
						$fieldKey => $fieldVlaue,
					],
					"where" => $where,
				]);
				//添加记录
				$text .= "管理员{$this->control['name']}修改了一条" . self::title . "：ID【{$id}】<br>";
				$x++;
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "修改了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] === '正常') {
					$warn = "删除失败：正常，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					delete(["table" => self::tableMotor, "where" => " eqid = '$id' "]);
					delete(["table" => self::tableDepr, "where" => " eqid = '$id' "]);
					delete(["table" => 'equipment_patrol_tpl', "where" => " eqid = '$id' "]);
					delete(["table" => 'equipment_record', "where" => " eqid = '$id' "]);
					delete(["table" => 'auditing_follow', "where" => " typeId = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 设备 - 变动记录
	 *
	 * @return bool|string
	 */
	public function record(): string
	{
		//生成查询语句
		$where = search([
			"=" => [
				'coid' => self::$coid,
				'eqid' => $this->get('id'),
			],
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
		$page  = $this->page(["table" => 'equipment_record', "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
		//获取记录
		foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $department = query('department', " id = '{$array['departmentId']}' ");
                        $row[] = $department['name'];
                        break;
                    case "time":
                        $row[] = self::formatDate($array['time']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
		//返回
		$json['html'] = "<div class='p-l-r-15'>" . $page['hint'] . "<form name='listForm'>" . space . $li . "</form>" . $page['button'] . clear . "</div>";
		return json_encode($json, 320);
	}

	/**
	 * 故障类型
	 *
	 * @return string
	 */
	public function failure(): string
	{
		$eqid = $this->get('id');
		$info = query('equipment', " id = '$eqid' ");
		if (!$this->power('equipment', "failure")) {
			$json['warn'] = "你没有查看权限";
		} elseif (empty($info['id'])) {
			$json['warn'] = "设备信息不存在";
		} else {
			// table
			$tpl    = query('equipment_patrol_tpl', " eqid = '{$info['id']}'  AND type = '故障类型' ");
			$tr[]   = ['故障类型', '故障等级', '操作'];
			$result = !empty($tpl['detail']) ? json_decode($tpl['detail'], true) : [];
            if(count($result) > 0) {
                foreach ($result as $k => $array) {
                    $array['list'] = $k + 1;
                    $tr[]          = $this->failureRow($array);
                }
            }else{
                $tr[] = $this->failureRow(['mxId'=>self::getId(), 'list'=>1]);
            }
            $table   = $this->tableMany(['tr' => $tr,'end' => true, 'displayFields' => false]);
			//生成页面
			$html = hidden(['name' => 'eqid', 'value' => $eqid]);
		}
		// 按钮
		$button = <<<EOT
		<div class="tab-button">
			<span onclick="subForm('failureForm', root+'control/adIndex.html?cla={$this->get('cla')}&fun=failureEdit')" class="spanButton li-btn-blue-bg">保存</span>
		</div>
EOT;
		//JS
		$js           = <<<EOT
		<script>
		  function addRow2(e){
		     $.post(root+'control/adIndex.php?cla={$this->get('cla')}&fun=addRowFailure',{},function (res){
		         $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
		     },'json');
		 }
		</script>
EOT;
        $json['html'] =
            "<div class='tab-box'>".
                $button .
                "<div class='tab-content p-l-r-10'>
                    <form name='failureForm'>" .
                    $html .
                    space .
                    $table .
                    "</form>" .
                    $js.
                "</div>
            </div>"
        ;
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 保养保存
	 *
	 * @return string
	 */
	public function failureEdit(): string
	{
		$types      = $this->post('type');
		$levels     = $this->post('level');
		$field      = [
			'eqid' => $this->post('eqid'),
			'type' => '故障类型',
		];
		$annotation = [
			'eqid' => '设备ID',
			'type' => '类型',
		];
		$rules      = [
			'eqid' => 'required',
			'type' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$title = '故障类型';
		$where = " eqid = '{$field['eqid']}' AND type='$title' ";
		$table = 'equipment_patrol_tpl';
		$page  = 'equipment';
		$menu  = $power = 'failure';
		$info  = query($table, $where);
		//判断
		if (!$this->power($page, $power)) {
			$json['warn'] = "你没有编辑" . $title . "的权限";
		}  else {
			$data = [];
			if (is_array($types)){
                foreach ($types as $k => $type) {
                    $data[] = [
                        'type'  => $type,
                        'level' => $levels[$k],
                    ];
                }
            }
			$field['detail'] = json_encode($data, 256);
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$field        = array_merge($field, [
					'id'   => self::getId(),
					'coid' => self::$coid,
					'stid' => self::$stid,
				]);
				$json['warn'] = static::insert(["table" => $table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => $table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . $title . " 设备id：【" . $field['eqid'] . '】';
				$this->logText(["type" => $page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=equipment&fun=detail&menu=$menu&id=" . $field['eqid'];
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

    /**
     * Desc : 故障
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function failureRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['type', 'level'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'failureRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow2(this)"),
            text(['name' => 'type[]', 'class' => 'text',  'title' => '请填写类型', 'value' => $array['type']]),
            select(['name' => 'level[]', 'class' => 'select','option' => explode('，', para('equipmentFailure')), 'title' => '请选择等级', 'value' => $array['level']]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * 故障类型添加一行
     *
     * @return string
     */
    public function addRowFailure(): string
    {
        $res = json_decode($this->failureRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

	/**
	 * 设备变动记录
	 *
	 * @param array $data
	 * @return string
	 */
	public static function equipmentRecord(array $data)
	{
		return static::insert([
			'table' => 'equipment_record',
			'field' => array_merge($data, [
				'id'   => self::getNo(),
				'coid' => self::$coid,
			]),
		]);
	}


	public static function qrBox($info, $department)
	{
		$url   = urlencode(root . self::page . '?url=' . $info['code']);
		$qrUrl = root . 'pay/wxpay/wxScanPng.php?url=' . $url;
		return '<div class="card-qr-box">
                    <div class="card-qr-img left">
                        <img class="logo img-center" src="' . root . 'img/svg/adloginIco.svg" alt="adloginIco" width="102">
                        <div class="card-qr-img-line"></div>
                        <img class="qr img-center" src="' . $qrUrl . '" alt="qr">
                    </div>
                    <div class="card-qr-ul left">
                        <p><span>设备编号：</span>' . $info['code'] . '</p>
                        <p><span>设备名称：</span>' . $info['name'] . '</p>
                        <p><span>规格型号：</span>' . $info['model'] . '</p>
                        <p><span>出厂日期：</span>' . $info['factoryDdate'] . '</p>
                        <p><span>使用部门：</span>' . $department['name'] . '</p>
                    </div>
                    </div>
                </div>';
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage(): string
	{
		$idArr = $this->get('body') ? explode(';', $this->get('body')) : [];
		$data  = [];
		foreach ($idArr as $id) {
			if(empty($id)){
				continue;
			}
			$info       = query(self::table, "id = '$id'");
			$depr       = query(self::tableDepr, " eqid = '$info[id]' ");
			$department = query('department', " id = '{$depr['departmentId']}' ");
			$data[]     = array_merge($info, [
				'department' => $department['name'],
				'logo'       => root . 'img/svg/adloginIco.svg',
				'qr'         => "source=" . self::table . "&id=" . $info['id'],
			]);
		}
		return (new printTemplateClass())->start(self::page, $data);
	}

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'设备类别',
                    'aliasName'=>'设备类别',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'设备编号',
                    'aliasName'=>'设备编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'设备名称',
                    'aliasName'=>'设备名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'设备用途',
                    'aliasName'=>'设备用途',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'生产厂家',
                    'aliasName'=>'生产厂家',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'出厂日期',
                    'aliasName'=>'出厂日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'进厂日期',
                    'aliasName'=>'进厂日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'安装日期',
                    'aliasName'=>'安装日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'投产日期',
                    'aliasName'=>'投产日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'安装图图号',
                    'aliasName'=>'安装图图号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'安装图存放位置',
                    'aliasName'=>'安装图存放位置',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'出厂编号',
                    'aliasName'=>'出厂编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'设备来源',
                    'aliasName'=>'设备来源',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'外形尺寸',
                    'aliasName'=>'外形尺寸',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'资产原值',
                    'aliasName'=>'资产原值',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'累计折旧',
                    'aliasName'=>'累计折旧',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'净残值',
                    'aliasName'=>'净残值',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'折旧方式',
                    'aliasName'=>'折旧方式',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'使用期限',
                    'aliasName'=>'使用期限',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'折旧期限',
                    'aliasName'=>'折旧期限',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'使用部门编号',
                    'aliasName'=>'使用部门编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'使用部门',
                    'aliasName'=>'使用部门',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'存放地点',
                    'aliasName'=>'存放地点',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'管理员编号',
                    'aliasName'=>'管理员编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'管理员',
                    'aliasName'=>'管理员',

                    'isMust'=>false,
                ],
            ]
        };
    }
}
